package com.yqw.onlineDocs.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yqw.onlineDocs.common.ErrorCode;
import com.yqw.onlineDocs.constant.CommonConstant;
import com.yqw.onlineDocs.exception.ThrowUtils;
import com.yqw.onlineDocs.mapper.DocumentTemplateMapper;
import com.yqw.onlineDocs.model.dto.documentTemplate.DocumentTemplateQueryRequest;
import com.yqw.onlineDocs.model.entity.DocumentTemplate;
import com.yqw.onlineDocs.model.entity.User;
import com.yqw.onlineDocs.model.vo.DocumentTemplateVO;
import com.yqw.onlineDocs.model.vo.UserVO;
import com.yqw.onlineDocs.service.DocumentTemplateService;
import com.yqw.onlineDocs.service.UserService;
import com.yqw.onlineDocs.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 文档模板服务实现
 * 
 */
@Service
@Slf4j
public class DocumentTemplateServiceImpl extends ServiceImpl<DocumentTemplateMapper, DocumentTemplate>
    implements DocumentTemplateService {

  @Resource
  private UserService userService;

  /**
   * 校验数据
   *
   * @param documentTemplate
   * @param add              对创建的数据进行校验
   */
  @Override
  public void validDocumentTemplate(DocumentTemplate documentTemplate, boolean add) {
    ThrowUtils.throwIf(documentTemplate == null, ErrorCode.PARAMS_ERROR);
    String name = documentTemplate.getName();
    String content = documentTemplate.getContent();
    String category = documentTemplate.getCategory();
    // 创建数据时，参数不能为空
    if (add) {
      ThrowUtils.throwIf(StringUtils.isBlank(name), ErrorCode.PARAMS_ERROR, "模板名称不能为空");
      ThrowUtils.throwIf(StringUtils.isBlank(content), ErrorCode.PARAMS_ERROR, "模板内容不能为空");
      ThrowUtils.throwIf(StringUtils.isBlank(category), ErrorCode.PARAMS_ERROR, "模板分类不能为空");
    }
    // 修改数据时，有参数则校验
    if (StringUtils.isNotBlank(name)) {
      ThrowUtils.throwIf(name.length() > 80, ErrorCode.PARAMS_ERROR, "模板名称长度不能超过80个字符");
      ThrowUtils.throwIf(name.length() < 2, ErrorCode.PARAMS_ERROR, "模板名称长度不能少于2个字符");
    }
    if (StringUtils.isNotBlank(content)) {
      ThrowUtils.throwIf(content.length() > 10000, ErrorCode.PARAMS_ERROR, "模板内容长度不能超过10000个字符");
    }
    if (StringUtils.isNotBlank(category)) {
      ThrowUtils.throwIf(category.length() > 50, ErrorCode.PARAMS_ERROR, "模板分类长度不能超过50个字符");
    }
  }

  /**
   * 获取查询条件
   *
   * @param documentTemplateQueryRequest
   * @return
   */
  @Override
  public QueryWrapper<DocumentTemplate> getQueryWrapper(DocumentTemplateQueryRequest documentTemplateQueryRequest) {
    QueryWrapper<DocumentTemplate> queryWrapper = new QueryWrapper<>();
    if (documentTemplateQueryRequest == null) {
      return queryWrapper;
    }
    // todo 从对象中取值
    Long id = documentTemplateQueryRequest.getId();
    String name = documentTemplateQueryRequest.getName();
    String content = documentTemplateQueryRequest.getContent();
    String category = documentTemplateQueryRequest.getCategory();
    Long userId = documentTemplateQueryRequest.getUserId();
    String sortField = documentTemplateQueryRequest.getSortField();
    String sortOrder = documentTemplateQueryRequest.getSortOrder();
    // todo 补充需要的查询条件
    // 模糊查询
    queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
    queryWrapper.like(StringUtils.isNotBlank(category), "category", category);
    queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
    // 精确查询
    queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
    queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
    // 排序规则
    queryWrapper.orderBy(SqlUtils.validSortField(sortField),
        sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
        sortField);
    return queryWrapper;
  }

  /**
   * 获取文档模板封装
   *
   * @param documentTemplate
   * @param request
   * @return
   */
  @Override
  public DocumentTemplateVO getDocumentTemplateVO(DocumentTemplate documentTemplate, HttpServletRequest request) {
    // 对象转封装类
    DocumentTemplateVO documentTemplateVO = DocumentTemplateVO.objToVo(documentTemplate);

    // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
    // region 可选
    // 1. 关联查询用户信息
    Long userId = documentTemplate.getUserId();
    User user = null;
    if (userId != null && userId > 0) {
      user = userService.getById(userId);
    }
    UserVO userVO = userService.getUserVO(user);
    documentTemplateVO.setUser(userVO);
    // endregion

    return documentTemplateVO;
  }

  /**
   * 分页获取文档模板封装
   *
   * @param documentTemplatePage
   * @param request
   * @return
   */
  @Override
  public Page<DocumentTemplateVO> getDocumentTemplateVOPage(Page<DocumentTemplate> documentTemplatePage,
      HttpServletRequest request) {
    List<DocumentTemplate> documentTemplateList = documentTemplatePage.getRecords();
    Page<DocumentTemplateVO> documentTemplateVOPage = new Page<>(documentTemplatePage.getCurrent(),
        documentTemplatePage.getSize(), documentTemplatePage.getTotal());
    if (CollUtil.isEmpty(documentTemplateList)) {
      return documentTemplateVOPage;
    }
    // 对象列表 => 封装对象列表
    List<DocumentTemplateVO> documentTemplateVOList = documentTemplateList.stream().map(documentTemplate -> {
      return DocumentTemplateVO.objToVo(documentTemplate);
    }).collect(Collectors.toList());

    // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
    // region 可选
    // 1. 关联查询用户信息
    Set<Long> userIdSet = documentTemplateList.stream().map(DocumentTemplate::getUserId).collect(Collectors.toSet());
    Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
        .collect(Collectors.groupingBy(User::getId));
    // endregion

    documentTemplateVOPage.setRecords(documentTemplateVOList);
    return documentTemplateVOPage;
  }

}
